<?php

class ProductController extends BaseController
{
    private $req;
    private $auth;

    public function init()
    {
        $this->req = $this->getRequest();
        if ($this->req->isXMLHttpRequest()) {
            Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
            $layout = Zend_Layout::getMvcInstance();
            if ($layout instanceof Zend_Layout) {
                $layout->disableLayout();
            }
        }
        // 全局搜索专用
        $this->view->breadcrumb = array(array(
            'url' => '/product/list',
            'name' => '实体奖品',
        ));
    }

    /**
     *
     */
    public function indexAction()
    {
        $this->redirect('/product/list');
    }


    /**
     * 实体奖品
     */
    public function listAction()
    {
        $product_biz = new \Biz\Product();
        $size = Page::ValidatePageSize($this->req->get('pageSize'), '/product/list'); //每页显示条数
        $now = $this->req->get('p') ? $this->req->get('p') : 1;//当前页数
        $where = array();
        $searchArr = array();
        $search_name = $this->req->get('search_name'); // 商品名称

        if (!empty($search_name)) {
            $searchArr['search_name'] = $search_name;
            $where[] = sprintf(' (`name` like "%%%s%%")', $search_name);
        }

        $product_list_result = $product_biz->getList($where, $now, $size);
        $page = new Page($product_list_result['total'], $size, $now, '/product/list?'.$this->makeUrl($searchArr), 2);
        $this->view->search_name = $search_name;
        $this->view->size = $size;
        $this->view->now = $now;
        $this->view->page = $page->showPage();
        $this->view->product_list = $product_list_result['lists'];
        $this->view->breadcrumb = array(array(
            'name' => '实体奖品',
        ));
    }


    /**
     * 新增商品
     */
    public function createAction()
    {
        $this->view->breadcrumb = array(array(
            'name' => '新增实体奖品',
        ));
    }

    /**
     * 上传商品图片
     * @return array
     */
    public function uploadImageAction()
    {
        $req = $this->getRequest();
        if ($req->isPost() && $req->isXMLHttpRequest() && $_FILES) {
            if (isset($_FILES['mypic']) && $_FILES['mypic']) {
                $suffix = $_FILES['mypic']['name'];
                $postfix = substr($suffix, -4);
                if ($_FILES["mypic"]['size'] > 2048000) {
                    return Response::Error(0, "图片大小不能超过2M");
                }
                $postfix = strtolower($postfix);
                if ($postfix == '.jpg' || $postfix == '.png' || $postfix == 'jpeg') {
                    $today = rand(100, 999);
                    $pic_name = date("YmdHis") . $today . $postfix;
                    $pic_url = \Util\Image::pcUpload(
                        array('name' => $pic_name,
                            'type' => $_FILES["mypic"]['type'],
                            'tmp_name' => $_FILES["mypic"]['tmp_name'],
                            'error' => $_FILES["mypic"]['error'],
                            'size' => $_FILES["mypic"]['size']
                        )
                    );
                    if ($pic_url == false ) {
                        return Response::Error(0, "上传图片出错！");
                    }
                    $arr = array(
                        'name' => $suffix,
                        'pic' => $pic_name,
                        'size' => $_FILES["mypic"]['size']
                    );
                    return Response::Success($arr);
                } else {
                    return Response::Error(0, "图片格式只支持jpg,jpeg,png格式！");
                }
            }
        }
    }

    /**
     * 新增商品
     */
    public function insertAction()
    {
        try {
            $product_name = $this->req->getPost('product_name');
            $text_description = $this->req->getPost('text_description');
            $type = $this->req->getPost('type');
            $total_num = $this->req->getPost('total_num');
            $portrait = $this->req->getPost('portrait');
            if($product_name == ''){
                return Response::Error(0, "商品名称不能为空！");
            }
            if($text_description == ''){
                return Response::Error(0, "商品描述不能为空！");
            }
            if($type == ''){
                return Response::Error(0, "请选择奖池！");
            }
            if($total_num == ''){
                return Response::Error(0, "奖品数量不能为空！");
            }
            if($portrait == ''){
                return Response::Error(0, "商品图片不能为空！");
            }
            $product_data = array(
                'name'=>$product_name,
                'description'=>$text_description,
                'type'=>$type,
                'total_num'=>$total_num,
                'portrait'=>$portrait
            );

            $product_biz = new \Biz\Product();
            $re = $product_biz->insert($product_data);
            if($re>0){
                return Response::Success(array(), '添加成功');
            }else{
                return Response::Error(0, '添加失败');
            }
        } catch (Exception $e) {
            return Response::Error(0, $e->getMessage());
        }
    }

    /**
     * 更新商品信息
     */
    public function updateAction()
    {

    }

    /**
     * 删除商品信息
     */
    public function deleteProductAction()
    {
        try {
            $product_id = $this->req->getPost('product_id');
            if (empty($product_id)) {
                return Response::Error(__LINE__, '商品id不能为空');
            }
            $product_biz = new \Biz\Product();
            $product_biz->delete($product_id);
            return Response::Success(array(), '删除商品成功');
        } catch (Exception $e) {
            return Response::Error($e->getCode(), $e->getMessage());
        }
    }

    private function dealImageList($image_list, $image_default_list)
    {
        $image_list_deal = array();
        if (!empty($image_list)) {
            $default_image_id = 0;
            foreach ($image_default_list as $image_id => $default_value) {
                if ($default_value == 1) {
                    $default_image_id = $image_id;
                    break;
                }
            }
            $sort = 0;
            foreach ($image_list as $image_id => $image_url) {
                $is_default = 0;
                if (empty($image_url)) {
                    continue;
                }
                $image_domain = \Util\Config::get('image_url','Common');
                if (strpos($image_url, $image_domain) !== false) {
                    $image_url_temp = str_replace($image_domain, '', $image_url);
                } else {
                    $image_url_temp = 'files/' . $image_url;
                }
                if ($image_id == $default_image_id) {
                    $is_default = 1;
                }
                $image_list_deal[] = array(
                    'icon_url' => $image_url_temp,
                    'is_default' => $is_default,
                    'sort' => $sort,
                );
                $sort++;
            }
        }
        return $image_list_deal;
    }

    /**
     * 商品详情
     */
    public function detailAction()
    {
        $this->view->title = '商品详情';
    }

    /**
     * 搜索商品
     */
    public function searchProductAction()
    {
        $customer_name = $this->req->getPost('product_name');
        $channel_id = $this->req->getPost('channel_id');
        if(!empty($type)){
            $where[] = " `channel_id` = '" . $channel_id . "' ";
        }
        $where[] = " `name` like '%" . $customer_name . "%' ";
        $product_biz = new \Biz\Product();
        $now = 1;
        $size = 10;
        $product_list_result = $product_biz->searchProduct($where, $now, $size);
        $product_list_deal = array();
        if (!empty($product_list_result['lists'])) {
            foreach ($product_list_result['lists'] as $product_info) {
                $product_list_deal[] = array(
                    'product_id' => $product_info['id'],
                    'product_name' => $product_info['name'],
                );
            }
        }
        return Response::Success($product_list_deal, '获取成功');
    }


    /**
     * 商品列表导出
     */
    public function exportAction()
    {
        try {
            // 检查请求
            if (!$this->req->isGet()) {
                return Response::Error(0, '请求方式错误');
            }
            $product_biz = new \Biz\Product();
            $size = Page::ValidatePageSize($this->req->get('pageSize'), '/product/list'); //每页显示条数
            $now = $this->req->get('p') ? $this->req->get('p') : 1;//当前页数
            $where = array();
            $searchArr = array();
            $search_name_code = $this->req->get('search_name_code'); // 商品名称/编码
            $search_brand_id = $this->req->get('search_brand_id'); // 商品分类id
            $search_status = $this->req->get('search_status');
            $search_channel_id = $this->req->get('search_channel_id'); // 商品渠道id
            if (!empty($search_name_code)) {
                $searchArr['search_name_code'] = $search_name_code;
                $where[] = sprintf(' (`name` like "%%%s%%" or `code` like "%%%s%%")', $search_name_code, $search_name_code);
            }
            if (!empty($search_brand_id)) {
                $searchArr['search_brand_id'] = $search_brand_id;
                $where[] = sprintf(' `brand_id`=%d', $search_brand_id);
            }
            $status_list = array_keys(\Orm\Product\ProductClass::getStatusList());
            if ($search_status !== NULL && in_array($search_status, $status_list)) {
                $searchArr['search_status'] = $search_status;
                $where[] = sprintf(' `status`=%d', $search_status);
            }
            if (!empty($search_channel_id)) {
                $searchArr['search_channel_id'] = $search_channel_id;
                $where[] = sprintf(' `channel_id`=%d', $search_channel_id);
            }

            $product_list_result = $product_biz->getAdminProductList($where, $now, $size);
            $total =  $product_list_result['total'];
            if($total>5000){
                throw new Exception('对不起，导出数据不能超过5千条');
            }
            $header = array( // Excel头
                '序号',
                /*'商品图片',*/
                '商品名称',
                '商品分类',
                '计量单位',
                '包装规格',
                '状态',
                '销售渠道',
            );
            \Util\Excel::setExcelHeader('商品列表', $header);
            $page_size = 100;
            $page_total = ceil($total / $page_size);
            for ($page_now = 1; $page_now <= $page_total; $page_now++) {
                $result = $product_biz->getAdminProductList($where, $page_now, $page_size);
                foreach ($result['lists'] as $k=>$product_info) {
                    $row_data = array(
                        '序号' => $k+1,
                        /*'商品图片' => $product_info['default_image_url'],*/
                        '商品名称' => $product_info['name'],
                        '商品分类' => $product_info['brand_name'],
                        '计量单位' => $product_info['unit_name'],
                        '包装规格' => $product_info['standard_string'],
                        '状态' => $product_info['status_name'],
                        '销售渠道' => $product_info['channel_name'],
                    );
                    \Util\Excel::setRow($row_data);
                }
                ob_flush();
                flush();
            }
            exit;
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
}